package com.shiyi.system.controller;


import com.shiyi.core.utils.result.Result;
import com.shiyi.core.vo.Menu;
import com.shiyi.system.annotation.OperaLog;
import com.shiyi.system.entity.SysMenu;
import com.shiyi.system.service.SysMenuService;
import com.shiyi.system.utils.EntityConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author shiyi
 * @since 2020-11-19
 */
@Api(value = "菜单表", tags = "菜单表")
@RestController
@RequestMapping("/system/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService service;


    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询所有菜单
     */
    @ApiOperation("查询所有菜单")
    @GetMapping("/listMenu")
    public Result<List<Menu>> listMenu() {
        List<Menu> menus = sysMenuService.listMenu();
        return Result.success(menus);
    }


    /**
     * 根据角色id查询菜单
     */
    @ApiOperation("根据角色id查询菜单")
    @GetMapping("/listMenusByRoleIds")
    public Result<List<Menu>> listMenusByRoleIds(@RequestParam("roleIds") List<Integer> roleIds) {
        List<Menu> menus = sysMenuService.listMenusByRoleIds(roleIds);
        return Result.success(menus);
    }

    /**
     * 新增菜单
     */
    @OperaLog(operaModule = "菜单管理", type = 1)
    @ApiOperation("新增菜单")
    @PostMapping("/insert")
    public Result<Object> insert(@RequestBody @Valid SysMenu menu, BindingResult res) {
        if (res.hasErrors()) {
            return Result.BindingError(res);
        }
        if (!service.getMenuByMenuName(menu.getMenuName())) {
            return Result.fail(EntityConstant.EXIST_MENU_NAME);
        }
        return service.insertMenu(menu) ? Result.success() : Result.fail();
    }

    /**
     * 修改菜单
     */
    @OperaLog(operaModule = "菜单管理", type = 2)
    @ApiOperation("修改菜单")
    @PostMapping("/update")
    public Result<Object> update(@RequestBody @Valid SysMenu menu, BindingResult res) {
        if (res.hasErrors()) {
            return Result.BindingError(res);
        }
        if (!service.getMenuByMenuNameAndId(menu.getMenuName(), menu.getId())) {
            return Result.fail(EntityConstant.EXIST_MENU_NAME);
        }
        return service.insertMenu(menu) ? Result.success() : Result.fail();
    }

    /**
     * 删除菜单
     */
    @OperaLog(operaModule = "菜单管理", type = 3)
    @ApiOperation("删除菜单")
    @DeleteMapping("/delete/{id}")
    public Result<Object> delete(@PathVariable Integer id) {
        return service.deleteMenu(id) ? Result.success() : Result.fail();
    }

}

